package fhq.hcmute.edu.vn.activities;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import fhq.hcmute.edu.vn.languages.Language;
import fhq.hcmute.edu.vn.message.MessageFactory;
import fhq.hcmute.edu.vn.message.MyMessage;
import fhq.hcmute.edu.vn.network.Network;
import fhq.hcmute.edu.vn.network.SendAndReceive;
import fhq.hcmute.edu.vn.util.BundleUtil;
import fhq.hcmute.edu.vn.util.HandlerRequestUtil;
import fhq.hcmute.edu.vn.util.ProjectUtil;

public class MainActivity extends Activity {

	public static final String WIFI_CONNECTED = "WIFI_CONNECTED";
	private Button btnConnect;
	private Network network;
	private WifiStateChangedReceiver wifiStateChangedReceiver;
	private boolean isShowWifiManager = true;
	private boolean isConnectedToWifi = false;
	private String languagePicked;
	private boolean isError = true;;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = new Bundle();
			Intent intent = new Intent(getApplicationContext(),
					WifiManagerActivity.class);
			switch (msg.what) {
			case HandlerRequestUtil.MAIN_ACTIVITY_REQUEST:
				MyMessage message = (MyMessage) msg.obj;
				if (message != null) {
					if (message.getType() == MessageFactory.RETURN) {
						if ((Boolean) message.getFirstData()) {
							intent = new Intent(getApplicationContext(),
									MainFunctions.class);
							startActivity(intent);
						}
					}
				} else {
					intent = new Intent(getApplicationContext(),
							BarcodeScannerActivity.class);
					startActivity(intent);
				}
				break;
			case WifiStateChangedReceiver.WIFI_ON:
				bundle.putBoolean(BundleUtil.WIFI_STATE, true);
				isConnectedToWifi = true;
				break;
			case WifiStateChangedReceiver.WIFI_OFF:
				bundle.putBoolean(BundleUtil.WIFI_STATE, false);
				isConnectedToWifi = false;
				if (isShowWifiManager) {
					startActivity(intent);
					isShowWifiManager = false;
				}
				break;
			case WifiStateChangedReceiver.WIFI_UNKNOWN:
				bundle.putBoolean(BundleUtil.WIFI_STATE, false);
				isConnectedToWifi = false;
				if (isShowWifiManager) {
					startActivity(intent);
					isShowWifiManager = false;
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public final void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Language.updateLanguageSystem(getBaseContext());
		setContentView(R.layout.activity_main);
		init();
		wifiStateChangedReceiver = new WifiStateChangedReceiver(handler);
	}

	@Override
	public final boolean onCreateOptionsMenu(final Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu_main_activity, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected final void onPause() {
		this.unregisterReceiver(wifiStateChangedReceiver);
		super.onPause();
	}

	@Override
	protected final void onResume() {
		this.registerReceiver(wifiStateChangedReceiver,
				new IntentFilter(
						WifiManager.WIFI_STATE_CHANGED_ACTION));
		super.onResume();
	}

	private void init() {
		btnConnect = (Button) findViewById(R.id.btnConnect);
		btnConnect.setOnClickListener(onConnectClick);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem item = menu.findItem(R.id.menuItemConnectManual);
		if (Network.getInstance().isConnected()) {
			item.setVisible(false);
		} else {
			item.setVisible(true);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public final boolean onOptionsItemSelected(final MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case R.id.menuItemConnectManual:
			intent =
					new Intent(getApplicationContext(),
							ConnectManualActivity.class);
			startActivity(intent);
			break;
		case R.id.menuItemChangeLanguage:
			intent =
					new Intent(getApplicationContext(), LanguageActivity.class);
			startActivityForResult(intent,
					ProjectUtil.REQUEST_CODE_PICK_LANGUAGE);
			break;
		case R.id.menuItemSetting:
			intent = new Intent(getApplicationContext(),
					WifiManagerActivity.class);
			Bundle bundle = new Bundle();
			bundle.putBoolean(WIFI_CONNECTED, isConnectedToWifi);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.menuItemAbout:
			break;
		default:
			exit();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void
			onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case ProjectUtil.REQUEST_CODE_PICK_LANGUAGE:
			if (resultCode == ProjectUtil.RESULT_CODE_PICK_LANGUAGE_CHANGE) {
				Bundle bundle = data.getExtras();
				languagePicked = bundle.getString(Language.KEY_LANGUAGE);
				Language.saveLanguage(getApplicationContext(), languagePicked);
				showConfirmRestartDialog();
			}
			break;
		default:
			break;
		}
	}

	private void showConfirmRestartDialog() {
		String title = getResources().getString(
				R.string.AlertDialog_Change_Language_Message);
		String positiveButton = getResources().getString(
				R.string.AlertDialog_Restart_Now);
		String negativeButton = getResources().getString(
				R.string.AlertDialog_Restart_Later);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton(positiveButton,
						positiveButton())
				.setNegativeButton(negativeButton,
						null);
		AlertDialog alert = builder.create();
		alert.show();
	}

	private DialogInterface.OnClickListener positiveButton() {
		return new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				Intent intent = new Intent(getApplicationContext(),
						MainActivity.class);
				startActivity(intent);
				MainActivity.this.finish();
				Language.updateLanguageSystem(getApplicationContext());
			}
		};
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void exit() {
		MyMessage message = MessageFactory.createStopMessage();
		network = Network.getInstance();
		if (network != null && network.isConnected()) {
			try {
				network.sendToServer(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		network.destroyAsynTask();
		network = null;
		finish();
	}

	@Override
	public final boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				exit();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private OnClickListener onConnectClick = new OnClickListener() {

		public void onClick(final View v) {
			isError = true;
			if (isConnectedToWifi) {
				network = Network.getInstance();
				if (network != null) {
					MyMessage message = MessageFactory.createPingMessage();
					if (network.isConnected() && !network.isClosed()) {
						SendAndReceive fromServer =
								new SendAndReceive(
										MainActivity.this,
										HandlerRequestUtil.MAIN_ACTIVITY_REQUEST,
										handler);
						fromServer.execute(message);
						isError = false;
					}
				}
				if (isError) {
					Intent intent = new Intent(getApplicationContext(),
							BarcodeScannerActivity.class);
					startActivity(intent);
				}
			} else {
				Intent intent = new Intent(getApplicationContext(),
						WifiManagerActivity.class);
				startActivity(intent);
			}
		}
	};
}
